package com.zhai.boot.interceptor;


import com.zhai.boot.annotation.ControllerLog;
import com.zhai.boot.util.DateUtil;
import com.zhai.boot.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @package: com.zhai.boot.interceptor
 * @project-name: zhai-boot
 * @description: 控制层接口日志
 * @author: Created by 翟凤玺
 * @create-datetime: 2018-10-12 16:13
 */

@Aspect
@Configuration
public class ControllerLogInterceptor {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 毫秒
     */
    private static final String ELAPSED_TIME_UNIT = "ms";

    @Around("execution(public * *(..)) && @annotation(com.zhai.boot.annotation.ControllerLog)")
    public void interceptor(ProceedingJoinPoint pjp) throws Throwable {

        LocalDateTime startDateTime = DateUtil.getCurrentLocalDateTime();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        ControllerLog controllerLog = method.getAnnotation(ControllerLog.class);
        LocalDateTime endDateTime = DateUtil.getCurrentLocalDateTime();
        String mongo = controllerLog.mongo();
        String operate = controllerLog.operate();
        String remark = controllerLog.remark();
        Object args = pjp.getArgs();
        Object result = pjp.proceed();
        String startTime = DateUtil.fmtLocalDateTimeToStr(startDateTime, DateUtil.DATETIME_FMT_3);
        String endTime = DateUtil.fmtLocalDateTimeToStr(endDateTime, DateUtil.DATETIME_FMT_3);
        Long elapsedTime = DateUtil.betweenMillis(endDateTime, startDateTime);
        Map<String, Object> mongoInsert = new HashMap<>(7);
        mongoInsert.put("operate" , operate);
        mongoInsert.put("args" , args);
        mongoInsert.put("result" , result);
        mongoInsert.put("startTime" , startTime);
        mongoInsert.put("endTime" , endTime);
        mongoInsert.put("elapsedTime" , StringUtil.join(elapsedTime, ELAPSED_TIME_UNIT));
        mongoInsert.put("remark" , remark);
        mongoTemplate.insert(mongoInsert,mongo);
    }


}
